"""
配置加载器
用于加载和管理配置文件
"""

import os
import yaml
import json
import logging

logger = logging.getLogger(__name__)

class ConfigLoader:
    """配置加载器，用于加载和管理配置文件"""
    
    def __init__(self, config_path='config/config.yaml'):
        """
        初始化配置加载器
        
        Args:
            config_path: 配置文件路径
        """
        self.config_path = config_path
        self.config = self.load_config(config_path)
        
    def load_config(self, config_path):
        """
        加载配置文件
        
        Args:
            config_path: 配置文件路径
            
        Returns:
            dict: 配置信息
        """
        try:
            with open(config_path, 'r', encoding='utf-8') as f:
                if config_path.endswith('.yaml') or config_path.endswith('.yml'):
                    config = yaml.safe_load(f)
                else:
                    config = json.load(f)
            logger.info(f"成功加载配置文件: {config_path}")
            return config
        except Exception as e:
            logger.error(f"加载配置文件失败: {e}")
            return {}
            
    def get(self, section, default=None):
        """
        获取配置节
        
        Args:
            section: 配置节名称
            default: 默认值
            
        Returns:
            配置节内容
        """
        return self.config.get(section, default)
        
    def get_nested(self, *keys, default=None):
        """
        获取嵌套配置
        
        Args:
            keys: 多级配置路径
            default: 默认值
            
        Returns:
            配置内容
        """
        current = self.config
        for key in keys:
            if isinstance(current, dict) and key in current:
                current = current[key]
            else:
                return default
        return current
        
    def reload(self):
        """重新加载配置文件"""
        self.config = self.load_config(self.config_path)
        return self.config
        
    def save(self, config_path=None):
        """
        保存配置到文件
        
        Args:
            config_path: 配置文件路径，如果为None则保存到当前配置文件
            
        Returns:
            bool: 是否保存成功
        """
        if config_path is None:
            config_path = self.config_path
            
        try:
            with open(config_path, 'w', encoding='utf-8') as f:
                if config_path.endswith('.yaml') or config_path.endswith('.yml'):
                    yaml.dump(self.config, f, default_flow_style=False, allow_unicode=True)
                else:
                    json.dump(self.config, f, indent=2, ensure_ascii=False)
            logger.info(f"成功保存配置文件: {config_path}")
            return True
        except Exception as e:
            logger.error(f"保存配置文件失败: {e}")
            return False 